package cn.nexd.app.collector.util;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.widget.Toast;

import com.pgyersdk.crash.PgyCrashManager;
import com.pgyersdk.javabean.AppBean;
import com.pgyersdk.update.PgyUpdateManager;
import com.pgyersdk.update.UpdateManagerListener;

import cn.nexd.app.collector.BuildConfig;

/**
 * Created by wangxu on 16/12/5.
 */
public class PgyUtil {

    private static final String TAG = "PgyUtil";

    private static PgyUtil ourInstance = new PgyUtil();

    public static PgyUtil getInstance() {
        return ourInstance;
    }

    private PgyUtil() {
    }

    private static boolean release = !BuildConfig.DEBUG;


    public void register(Context context) {
        if (release) {
            PgyCrashManager.register(context);
        }
    }

    public void unRegister() {
        if (release) {
            PgyCrashManager.unregister();
        }
    }

    public void reportCaughtException(Context context, Exception exception) {
        if (release) {
            PgyCrashManager.reportCaughtException(context, exception);
        }
    }

    public void checkUpdate(final Activity activity) {
        if (release) {
            PgyUpdateManager.register(activity, new UpdateManagerListener() {
                @Override
                public void onNoUpdateAvailable() {
                    Toast.makeText(activity, "已是最新版本", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onUpdateAvailable(String result) {
                    // 将新版本信息封装到AppBean中
                    final AppBean appBean = getAppBeanFromString(result);
                    new AlertDialog.Builder(activity)
                            .setTitle("更新")
                            .setMessage("有新版本发现，是否更新？")
                            .setNegativeButton(
                                    "确定",
                                    new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(
                                                DialogInterface dialog,
                                                int which) {
                                            startDownloadTask(
                                                    activity,
                                                    appBean.getDownloadURL());
                                        }
                                    }).show();
                }
            });
        }
    }
}
